<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数组操作</title>
</head>

<body>
  <script>
    var data = [{
      "province": "浙江",
      "city": "杭州",
      "name": "西湖"
    }, {
      "province": "四川",
      "city": "成都",
      "name": "锦里"
    }, {
      "province": "四川",
      "city": "成都",
      "name": "方所"
    }, {
      "province": "四川",
      "city": "阿坝",
      "name": "九寨沟"
    }]
    var keys = ['province', 'city', 'name']

    // var data = [{
    //   "value": "浙江",
    //   "children": [{
    //     "value": "杭州",
    //     "children": [{
    //       "value": "西湖"
    //     }]
    //   }]
    // }, {
    //   "value": "四川",
    //   "children": [{
    //     "value": "成都",
    //     "children": [{
    //       "value": "锦里"
    //     }, {
    //       "value": "方所"
    //     }]
    //   }, {
    //     "value": "阿坝",
    //     "children": [{
    //       "value": "九寨沟"
    //     }]
    //   }]
    // }]
    var transObject = function (tableData, keys) {
      let hashTable = {}, res = []
      for (let i = 0; i < tableData.length; i++) {
        let arr = res, cur = hashTable
        for (let j = 0; j < keys.length; j++) {
          let key = keys[j], filed = tableData[i][key]
          if (!cur[filed]) {
            let pusher = {
              value: filed
            }, tmp
            if (j !== (keys.length - 1)) {
              tmp = []
              pusher.children = tmp
            }
            cur[filed] = { $$pos: arr.push(pusher) - 1 }
            cur = cur[filed]
            arr = tmp
          } else {
            cur = cur[filed]
            arr = arr[cur.$$pos].children
          }
        }
      }
      return res
    }
    console.log(transObject(data, keys));

    // 给你n个名字串，然后进行m次点名，
    // 每次你需要回答“名字不存在”、“第一次点到这个名字”、“已经点过这个名字”之一。

  </script>
</body>

</html>